/*
登录 api 接口
实现登录操作，返回 token 到前端
*/

package v1

import (
    // "fmt"
    "net/http"
    "time"

    "gitee.com/keeving/quanta-test-cat/middleware"
    "gitee.com/keeving/quanta-test-cat/model"
    "gitee.com/keeving/quanta-test-cat/utils/errmsg"
    "github.com/gin-gonic/gin"
    "github.com/golang-jwt/jwt/v5"
)

// Login 后台登陆
// func Login(c *gin.Context) {
//     var formData model.User
//     // _ = c.ShouldBindJSON(&formData)

//     var token string
//     var code int

//     formData, code = model.CheckLogin(formData.Username, formData.Password)

//     if code == errmsg.SUCCESS {
//         setToken(c, formData)
//     } else {
//         c.JSON(http.StatusOK, gin.H{
//             "status":  code,
//             "data":    formData.Username,
//             "id":      formData.ID,
//             "message": errmsg.GetErrMsg(code),
//             "token":   token,
//         })
//     }

// }

// LoginFront 前台登录
func LoginFront(c *gin.Context) {
    var formData model.User
    _ = c.ShouldBindJSON(&formData)
    var code int
    var token string

    formData, code = model.CheckLoginFront(formData.Username, formData.Password)
    
    if code == errmsg.SUCCESS {
        setToken(c, formData)
    } else {
        c.JSON(http.StatusOK, gin.H{
            "code":  code,
            "username":    formData.Username,
            "id":      formData.ID,
            "msg":      errmsg.GetErrMsg(code),
            "data":   token,
        })
    }
}

// token生成函数
// 使用 JWT
func setToken(c *gin.Context, user model.User) {
    j := middleware.NewJWT()
    claims := middleware.MyClaims{
        Username: user.Username,
        RegisteredClaims: jwt.RegisteredClaims{
            NotBefore: jwt.NewNumericDate(time.Now()),
            ExpiresAt: jwt.NewNumericDate(time.Now().Add(7 * 24 * time.Hour)),
            Issuer:    "GinBlog",
        },
    }

    token, err := j.CreateToken(claims)

    if err != nil {
        c.JSON(http.StatusOK, gin.H{
            "code":  errmsg.ERROR,
            "msg": errmsg.GetErrMsg(errmsg.ERROR),
            "token":   token,
        })
    }

    c.JSON(http.StatusOK, gin.H{
        "code":  200,
        "username":    user.Username,
        "id":      user.ID,
        "msg": errmsg.GetErrMsg(200),
        "data":   token,
    })
}
